package com.yoomiito.app.widget

import android.content.Context
import androidx.appcompat.widget.AppCompatTextView
import android.util.AttributeSet
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.AnimationSet
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.oil.OilDiscount
import com.yoomiito.app.saveDecimal2
import com.yoomiito.app.utils.L
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

class AnimationTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null,defStyleAttr: Int = 0)
    :AppCompatTextView(context,attrs,defStyleAttr){
    private var  disposable: Disposable?=null
    fun setData(data:List<OilDiscount>){
        if(disposable!=null){
            disposable?.dispose()
            this.clearAnimation()
        }
        disposable = Observable.interval(0, 7000, TimeUnit.MILLISECONDS)
                .map{
                    L.i("时间：$it")
                    val po = (it % data.size).toInt()
                    L.i("计算的位置: $po")
                    data[po]
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext {
                    L.i("内容：$it")
                    if (this.visibility == View.GONE) {
                        L.i("隐藏后显示")
                        this.visibility = View.VISIBLE
                    }
                    L.i("淡入动画开始")
                    this.text = "${it.nickname.subSequence(0,1)}** 加油节省了¥${(it.money.toDouble()/100).toString().saveDecimal2()}"
                    val aset = AnimationSet(true)
                    val aa = AlphaAnimation(0f, 1f)
                    aa.duration = 500
                    aset.addAnimation(aa)
                    aset.fillAfter = true
                    this.startAnimation(aset)
                }
                .delay(4, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
//                .compose((context as BaseActivity<*>).bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext {
                    L.i("消失动画开始")
                    val aset = AnimationSet(true)
                    val aa = AlphaAnimation(1f, 0f)
                    aa.duration = 500
                    aset.addAnimation(aa)
                    aset.fillAfter = true
                    this@AnimationTextView.startAnimation(aset)
                }
                .subscribe()
    }
}